package com.yanghui.dtracing.core.plugin.interceptor;

import com.yanghui.dtracing.core.EnhancedInstance;
import com.yanghui.dtracing.core.exception.PluginException;
import com.yanghui.dtracing.core.log.ILog;
import com.yanghui.dtracing.core.log.LogManager;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.This;

public class ConstructIntercept {

    private final IConstructorInterceptor interceptor;
    
    private static final ILog log = LogManager.getLogger(ConstructIntercept.class);

    public ConstructIntercept(String constructorInterceptorClassName,ClassLoader classLoader){
        try{
            this.interceptor = InterceptorInstanceLoader.load(constructorInterceptorClassName,classLoader);
        }catch (Throwable t){
        	log.error("IConstructorInterceptor load fail.", t);
            throw new PluginException("Can't create IConstructorInterceptor.",t);
        }
    }

    @RuntimeType
    public void intercept(@This Object obj, @AllArguments Object[] allArguments){
        try{
            EnhancedInstance enhancedInstance = (EnhancedInstance)obj;
            this.interceptor.onConstructor(enhancedInstance,allArguments);
        }catch (Throwable t){
            log.error("ConstructInterceptorDecorate failure.",t);
        }
    }
}
